using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BaLs.Models;
using System.Net;
using System.IO;
using System.Data.Linq;
using MvcPaging;


namespace BaLs.Controllers
{
    public class LinkController : Controller
    {
        //
        // GET: /Link/
        
        private const int defaultPageSize = 10;

        public ActionResult Index(int? page)
        {

            IList<Link> userLinks = new List<Link>();
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;

            BaLsRespository res = new BaLsRespository();

            if (Session["user"] == null)
            {
                ViewData["Message"] = "Latest public links";                
                userLinks = res.GetAllPublicLink().ToList<Link>();
                return View("Index", userLinks.ToPagedList(currentPageIndex, defaultPageSize));
            }
            else
            {
                ViewData["Message"] = "Links for " + Session["user"].ToString();
                userLinks = res.GetLinkByUser(Session["user"].ToString()).ToList<Link>();
                return View("Index", userLinks.ToPagedList(currentPageIndex, defaultPageSize));                
            }
        }

        //
        // GET: /Link/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }


        public ActionResult DeliciousImport()
          {
              return View();
          }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeliciousImport(FormCollection form)
        {
            if (!isLogin())
                return RedirectToAction("LogOn", "Account");
            else
            {

                Delicious.Connection.Username = Request.Form["DelUserName"].ToString();
                Delicious.Connection.Password = Request.Form["DelPassword"].ToString();

                List<Delicious.Post> postList = Delicious.Post.Get();

                foreach (Delicious.Post post in postList)
                  {
                      if (!isPostExist(post))
                          addLinkFromDelicious(post);
                  }
                BaLsRespository res=new BaLsRespository();                                
                return RedirectToAction("Index");
            }

            
        }

        public ActionResult url(string url, int? page)
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            if (url != null)
                Session["userURL"] = url;
            
           IList<Link> userLinks = new List<Link>();
           int currentPageIndex = page.HasValue ? page.Value - 1 : 0;

           if (Session["userURL"] != null)
            {
                BaLsRespository res = new BaLsRespository();
                user usr = res.GetUser(Session["userURL"].ToString());

                if (usr == null)
                {
                    ViewData["Message"] = "The requested url is not found!";  
                    userLinks=res.GetAllPublicLink().ToList<Link>();
                    return View("Index", userLinks.ToPagedList(currentPageIndex, defaultPageSize));
                }
                else
                {
                    if (Session["user"] != null && Session["user"].ToString().Equals(url))
                    {
                        ViewData["Message"] = "Links for " + Session["userURL"].ToString();                       
                        userLinks = res.GetLinkByUser(Session["userURL"].ToString()).ToList<Link>();
                        return View("Index", userLinks.ToPagedList(currentPageIndex, defaultPageSize));
                    }
                    else
                    {
                        ViewData["Message"] = "Public links for " + Session["userURL"].ToString();
                        userLinks =  res.GetPublicLinkByUser(Session["userURL"].ToString()).ToList<Link>();
                        return View("Index", userLinks.ToPagedList(currentPageIndex, defaultPageSize));
                    }

                }
            }

            

            return View();
        }
        //
        // GET: /Link/Create

        public ActionResult Create()
        {
            if (!isLogin())
                return RedirectToAction("LogOn", "Account");
            else
            {
                ViewData["url"] = string.Empty;
                return View();
            }
        } 

        //for search links based on tags

        public ActionResult Search(String searchTag)
        {
            EntitySet<Tag> tags = getTags(searchTag);
            BaLsRespository res = new BaLsRespository();

            return View("Index", res.GetLinkByTags(tags));
            
        }

        
        // POST: /Link/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateURL(FormCollection collection)
        {                        
            try
            {
                // TODO: Add insert logic here
                Link link = new Link();
                string k = Request.Form["url"];
                ViewData["url"] = k;
                link.url = k;
                link.title = GetTitle(k);
                
                return View("Create",link);
            }
            catch
            {
                return View("Index");
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                if (Request.Form["state"].Equals("0"))
                { // TODO: Add insert logic here
                    Link link = new Link();
                    string k = Request.Form["url"];
                    ViewData["url"] = k;
                    link.url = k;
                    link.title = GetTitle(k);

                    return View(link);
                }
                else
                {
                    
                    BaLsRespository res = new BaLsRespository();

                    Link link = new Link();
                    link.url = Request.Form["url"];
                    link.title = Request.Form["title"];
                    link.notes = Request.Form["notes"];
                    link.owner = this.Session["user"].ToString();
                    char flag=(char)Request.Form["private_flag"].ToCharArray()[0];
                    link.private_flag = flag;
                    link.create_date = DateTime.Now;
                    link.Tags = getTags(Request.Form["tag"]);
                    res.Add(link);
                    res.Save();

                    
                    return RedirectToAction("Index");
                }
            }
            catch(Exception ex)
            {
                return View(ex.Message);
            }
        }


        private EntitySet<Tag> getTags(string strTag)
        {
            EntitySet<Tag> tagSet = new EntitySet<Tag>();
            Tag tagItem;
            string[] str = strTag.Split();
            foreach (string tag in str)
              {
                  tagItem = new Tag();
                  tagItem.tag_desc = tag;
                  tagSet.Add(tagItem);
              }
            return tagSet;
        }

        private EntitySet<Tag> getTags(string[] strTag)
        {            
            EntitySet<Tag> tagSet = new EntitySet<Tag>();
            if (strTag == null) return tagSet;

            Tag tagItem;            
            foreach (string tag in strTag)
            {
                tagItem = new Tag();
                tagItem.tag_desc = tag;
                tagSet.Add(tagItem);
            }
            return tagSet;
        }

        //
        // GET: /Link/Edit/5
 
        public ActionResult Edit(int id)
        {
            BaLsRespository db=new BaLsRespository();
            Link link = db.GetLink(id);

            return View(link);
        }

        //
        // POST: /Link/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                BaLsRespository db = new BaLsRespository();
                Link link = db.GetLink(id);
                link.notes = Request.Form["notes"];
                link.title = Request.Form["title"];
                link.Tags = getTags(Request.Form["tag"]);
                
                db.Save();                

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        private string GetTitle(string url)
        {
            try
            {
                WebRequest req = HttpWebRequest.Create(url);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                StreamReader strm = new StreamReader(resp.GetResponseStream());
                string contents = strm.ReadToEnd();

                int start = contents.IndexOf("<title>") + 7;
                int end = contents.IndexOf("</title>");

                return contents.Substring(start, end - start).Trim();
            }
            catch (Exception)
            { return ""; }

            
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(string ids)
        {            
            BaLsRespository res = new BaLsRespository();
            string id = Request["ids"].ToString();
            Link linkToDelete = res.GetLink(int.Parse(id));            
            res.Delete(linkToDelete);
            res.Save();

            //return RedirectToAction("Index","Link");
            Response.Write("Success");
            return null;
        }

        public bool isLogin()
        {
            if ((this.Session["user"] == null))
                return false;
            else
            {
                return true;
            }
        }

        private bool isPostExist(Delicious.Post post)
        {
            BaLsRespository res = new BaLsRespository();

            if (res.isLinkExist(post.Href, Session["user"].ToString()))
                return true;
            else
              return false;
        }

        private void addLinkFromDelicious(Delicious.Post post)
        {
            BaLsRespository res = new BaLsRespository();

            Link link = new Link();
            if (post.Href.Length > 250 || post.Extended.Length > 250||post.Description.Length>250)
                return;
            link.url = post.Href;
            link.title = post.Description;
            link.notes = (post.Extended.Length > 255) ? (post.Extended.Substring(0, 250)) : post.Extended; ;
            link.owner = this.Session["user"].ToString();
            char flag = (char)(!post.Shared).ToString().ToCharArray()[0];
            link.private_flag = flag;
            link.create_date = DateTime.Parse(post.Time);
            link.Tags = getTags(post.Tags);
            res.Add(link);
            res.Save();
        
        
        }
        
    }
}
